#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFileDialog>
#include <QStatusBar>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setWindowTitle("自定义记事本");

    // 设置菜单栏
    QMenuBar* menuBar = this->menuBar();
    this->setMenuBar(menuBar);

    // 设置菜单
    QMenu* menu = new QMenu("文件");
    menuBar->addMenu(menu);

    // 设置菜单项
    QAction* action1 = new QAction("打开");
    QAction* action2 = new QAction("保存");
    menu->addAction(action1);
    menu->addAction(action2);

    // 设置输入框
    edit = new QPlainTextEdit();
    QFont font;
    font.setPixelSize(25);
    edit->setFont(font);
    this->setCentralWidget(edit);

    // 连接 QAction 信号槽
    connect(action1, &QAction::triggered, this, &MainWindow::handleAction1);
    connect(action2, &QAction::triggered, this, &MainWindow::handleAction2);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handleAction1()
{
    // 1. 弹出 "打开文件" 对话框，进行选择
    QString path = QFileDialog::getOpenFileName(this);

    // 2. 将文件名显示在状态栏上
    QStatusBar* statusBar = this->statusBar();
    statusBar->showMessage(path);

    // 3. 根据选择的路径，构造 QFile 对象并打开文件
    QFile file(path);
    bool ret = file.open(QIODevice::ReadOnly);
    if (!ret)
    {
        statusBar->showMessage(path + " 打开失败");
        return;
    }

    // 4. 读取文件
    QString text = file.readAll();

    // 5. 关闭文件
    file.close();

    // 6. 读取到的内容显示在对话框
    edit->setPlainText(text);

}

void MainWindow::handleAction2()
{
    // 1. 弹出 "保存文件" 对话框
    QString path = QFileDialog::getSaveFileName(this);

    // 2. 在状态栏显示文件名
    QStatusBar* statusBar = this->statusBar();
    statusBar->showMessage(path);

    // 3. 根据选择的路径，构造 QFile 对象并打开文件
    QFile file(path);
    bool ret = file.open(QIODevice::WriteOnly);
    if (!ret)
    {
        statusBar->showMessage(path + " 打开失败");
        return;
    }

    // 4. 写文件
    const QString& text = edit->toPlainText();
    file.write(text.toUtf8());

    // 5. 关闭文件
    file.close();

}

